<template>
    <div class="gantt-box" style="height: 100%" ref="ganttBox" v-resize="{ fun: Resize }">
        <!-- <div :id="`gantt_here-${uuid}`" :ref="`gantt_here-${uuid}`" :style="`width: 100%; height: ${ganttHeight}px;position:relative`"></div> -->
        <div :id="`gantt_here-${uuid}`" :ref="`gantt_here-${uuid}`" :style="`width: 100%; height: 100%;position:relative`"></div>
    </div>
</template>
<script>
import './js/gant.js';
import $ from 'jquery';
import props from '../props';
export default {
    props,
    data() {
        return {
            ganttHeight: undefined,
            myEvents: [],
            uuid: 'this.$_O.RandomUUID()',
            gantt: Gantt.getGanttInstance(),
        };
    },
    watch: {
        task(data) {
            console.log('task refresh', data);
            this.UpdateGaunt(data);
        },
    },
    mounted() {
        this.InitGaunt(`gantt_here-${this.uuid}`);
        this.UpdateGaunt(this.task);
    },
    beforeDestroyed() {
        this.detachEvent(myEvent);
    },
    methods: {
        Resize(el) {
            this.ganttHeight = this.$refs.ganttBox?.offsetHeight || 0;
        },
        dateToStr() {
            return this.gantt.date.date_to_str(this.gantt.config.task_date);
        },
        UpdateGaunt(data) {
            // 据说是不清有问题，博客上别人踩得坑
            this.gantt.clearAll();
            // 放在init内clearAll会一起清楚
            this.gantt.addMarker({
                start_date: new Date(),
                css: 'today',
                text: 'now',
                title: this.dateToStr(new Date()),
            });
            this.gantt.parse(data);
        },
        InitGaunt() {
            const that = this;
            this.gantt.plugins({
                drag_timeline: true,
                marker: true,
                // tooltip: true, // 悬浮提示
                // quick_info: true // 快速信息框
                auto_scheduling: that.autoScheduling,
            });

            this.gantt.templates.scale_cell_class = function (date) {
                if (!that.gantt.isWorkTime(date)) {
                    return 'weekend';
                }
            };
            this.gantt.templates.timeline_cell_class = function (item, date) {
                if (!that.gantt.isWorkTime(date)) {
                    return 'weekend';
                }
            };

            this.gantt.config.work_time = true;

            this.gantt.config.auto_scheduling = that.autoScheduling;
            this.gantt.config.auto_scheduling_strict = that.autoScheduling;
            this.gantt.config.auto_scheduling_compatibility = that.autoScheduling;

            this.gantt.config.date_format = '%d-%m-%Y';

            // 时间轴
            this.gantt.config.scales = [
                // { unit: "year", format: "" },
                { unit: 'month', format: '%Y年 %m月' },
                { unit: 'day', step: 1, format: '%D %j号' },
            ];

            // 允许在出现意外行为时显示错误警报
            this.gantt.config.show_errors = false;

            // 自动扩展时间刻度以适应所有显示的任务
            this.gantt.config.fit_tasks = true;

            // 双击开启默认编辑框禁用
            this.gantt.config.details_on_dblclick = false;

            // 单击开启默认编辑框禁用
            this.gantt.config.details_on_click = false;

            // 拖拽任务自动滚动
            this.gantt.config.autoscroll = true;

            //允许显示鼠标移动到进度条上时显示前后两个小圆点（是否显示依赖连线）
            this.gantt.config.show_links = this.showLinks;

            //自适应甘特图的尺寸大小, 使得在不出现滚动条的情况下, 显示全部任务，打开后不能占满100%
            // this.gantt.config.autosize = true;

            //只读模式：打开后不可以操作甘特图
            this.gantt.config.readonly = this.readonly;

            //本地化
            this.gantt.config.scale_height = 50; //设置时间刻度的高度和网格的标题
            this.gantt.templates.task_text = this.taskHtml;

            // this.gantt.templates.tooltip_text = function(start, end, task) {
            //     return (
            //         "<b>标题:</b> " +
            //         task.text +
            //         "<br/><span>开始:</span> " +
            //         that.gantt.templates.tooltip_date_format(start) +
            //         "<br/><span>结束:</span> " +
            //         that.gantt.templates.tooltip_date_format(end) +
            //         "<br/><span>进度:</span> " +
            //         Math.round(task.progress * 100) +
            //         "%"
            //     );
            // };
            if (this.useDateArr) {
                this.gantt.config.start_date = new Date(this.dateArr[0]);
                this.gantt.config.end_date = new Date(this.dateArr[1]);
            }

            // 允许显示超过时间刻度任务
            this.gantt.config.show_tasks_outside_timescale = true;
            // 表格操作列点击事件
            window.ClickMenu = function (id, type) {
                let targetTask = that.gantt.getTask(id);
                switch (type) {
                    default:
                        that.$emit(type, targetTask);
                        break;
                }
            };
            this.gantt.config.columns = [...this.gridColumns];
            // if (this.columnButton.length) {
            //     let str = task => {
            //         return this.columnButton.reduce((pre, cur) => {
            //             pre += `<i class="september ${cur.icon}" title='${cur.name}' style='cursor:pointer;margin-right:4px' data-action="${cur.key}" onclick="ClickMenu('${task.id}','${cur.key}')"></i>`;
            //             return pre;
            //         }, '');
            //     };
            //     this.gantt.config.columns.push({
            //         name: 'buttons',
            //         label: `<div class="gantt_grid_head_cell gantt_grid_head_add" title='添加' onclick="ClickMenu('','add')"></div>`,
            //         width: 75,
            //         template: str,
            //     });
            // }

            this.gantt.i18n.setLocale({
                date: {
                    month_full: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                    month_short: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                    day_full: ['日', '一', '二', '三', '四', '五', '六'],
                    day_short: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
                },
                //  https://docs.dhtmlx.com/gantt/desktop__localization.html 本土化
            });
            this.AddEvents();
            this.gantt.init(`gantt_here-${this.uuid}`);
        },
        AddEvents() {
            let that = this;
            let onMouseMove = this.gantt.attachEvent('onMouseMove', function (id, e) {
                if (!id) {
                    that.gantt.unselectTask();
                    return;
                }
                that.gantt.selectTask(id);
            });
            this.myEvents.push(onMouseMove);
            let onTaskCreated = this.gantt.attachEvent('onTaskCreated', e => {
                // console.log(e);
                return false;
            });
            this.myEvents.push(onTaskCreated);

            let onLinkDblClick = this.gantt.attachEvent('onLinkDblClick', function (id, item) {
                that.$emit('onLinkDblClick', id, item);
                return false;
            });
            this.myEvents.push(onLinkDblClick);
            let onTaskDblClick = this.gantt.attachEvent('onTaskDblClick', function (id, e) {
                that.$emit('onTaskDblClick', that.gantt.getTask(id));
                return false;
            });
            this.myEvents.push(onTaskDblClick);
            // let onBeforeAutoSchedule = this.gantt.attachEvent(
            //     "onBeforeAutoSchedule",
            //     function() {
            //         return true;
            //     }
            // );
            // this.myEvents.push(onBeforeAutoSchedule);
            // let onAfterTaskAutoSchedule = this.gantt.attachEvent(
            //     "onAfterTaskAutoSchedule",
            //     function(task, new_date, constraint, predecessor) {}
            // );
            // this.myEvents.push(onAfterTaskAutoSchedule);
        },
        detachEvent(myEvent) {
            myEvent.forEach(ev => {
                this.gantt.detachEvent(ev);
            });
        },
    },
};
</script>
